import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'action.dart';
import 'item/state.dart';
import 'state.dart';

Reducer<HomeworkListState> buildReducer() {
  return asReducer(
    <Object, Reducer<HomeworkListState>>{
      HomeworkListAction.loaded: _loaded,
      HomeworkListAction.loading: _loading,
      HomeworkListAction.listResult: _listResult,
      HomeworkListAction.deleted: _deleted,
      HomeworkListAction.selectClass: _selectClass,
      HomeworkListAction.classes: _classes,
    },
  );
}

HomeworkListState _loading(HomeworkListState state, Action action) {
  return state.clone()..isLoading = true;
}

HomeworkListState _loaded(HomeworkListState state, Action action) {
  return state.clone()..isLoading = false;
}

HomeworkListState _listResult(HomeworkListState state, Action action) {
  final Map<String, dynamic> data = action.payload;
  if (data == null) {
    return state;
  }

  int pageIndex = data['pageIndex'];
  final HomeworkListState newState = state.clone()
    ..pageTotal = data['pageTotal']
    ..pageIndex = pageIndex;

  if (pageIndex == GlobalState.firstPageIndex + 1) {
    newState.items = data['items']; // reset if first page
  } else {
    newState.items.addAll(data['items']);
  }

  return newState;
}

HomeworkListState _deleted(HomeworkListState state, Action action) {
  String code = action.payload;
  final HomeworkListState newState = state.clone();
  newState.items.removeWhere((HomeworkState state) => state.id == code);
  return newState;
}

HomeworkListState _selectClass(HomeworkListState state, Action action) {
  return state.clone()..currentClassId = action.payload;
}

HomeworkListState _classes(HomeworkListState state, Action action) {
  return state.clone()..classes = action.payload;
}
